package com.aiguigu.lottery.user.controller;

import com.aiguigu.lottery.common.entity.UserEntity;
import com.aiguigu.lottery.common.vo.LoginResponse;
import com.aiguigu.lottery.common.utils.JwtUtils;
import com.aiguigu.lottery.user.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 用户控制器
 */
@RestController
@RequestMapping("/users")
@CrossOrigin(origins = "*")
public class UserController {
    
    private static final Logger logger = LoggerFactory.getLogger(UserController.class);
    
    @Autowired
    private UserService userService;
    
    @Autowired
    private JwtUtils jwtUtils;
    
    /**
     * 用户登录
     */
    @PostMapping("/login")
    public ResponseEntity<Map<String, Object>> login(@RequestBody UserEntity user) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            logger.info("用户登录请求: {}", user.getUsername());
            
            if (!StringUtils.hasText(user.getUsername()) || !StringUtils.hasText(user.getPassword())) {
                response.put("code", 0);
                response.put("msg", "用户名和密码不能为空");
                return ResponseEntity.badRequest().body(response);
            }
            
            LoginResponse loginResponse = userService.login(user.getUsername(), user.getPassword());
            
            if (loginResponse != null) {
                response.put("code", 1);
                response.put("msg", "登录成功");
                response.put("data", loginResponse);
                logger.info("用户 {} 登录成功", user.getUsername());
            } else {
                response.put("code", 0);
                response.put("msg", "用户名或密码错误");
                logger.warn("用户 {} 登录失败：用户名或密码错误", user.getUsername());
            }
            
        } catch (Exception e) {
            logger.error("登录过程中发生错误", e);
            response.put("code", 0);
            response.put("msg", "登录失败，请稍后重试");
        }
        
        return ResponseEntity.ok(response);
    }
    
    /**
     * 用户注册
     */
    @PostMapping("/register")
    public ResponseEntity<Map<String, Object>> register(@RequestBody UserEntity user) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            logger.info("用户注册请求: {}", user.getUsername());
            
            if (!StringUtils.hasText(user.getUsername()) || !StringUtils.hasText(user.getPassword())) {
                response.put("code", 0);
                response.put("msg", "用户名和密码不能为空");
                return ResponseEntity.badRequest().body(response);
            }
            
            boolean success = userService.register(user);
            
            if (success) {
                response.put("code", 1);
                response.put("msg", "注册成功");
                logger.info("用户 {} 注册成功", user.getUsername());
            } else {
                response.put("code", 0);
                response.put("msg", "用户名已存在");
                logger.warn("用户 {} 注册失败：用户名已存在", user.getUsername());
            }
            
        } catch (Exception e) {
            logger.error("注册过程中发生错误", e);
            response.put("code", 0);
            response.put("msg", "注册失败，请稍后重试");
        }
        
        return ResponseEntity.ok(response);
    }
    
    /**
     * 获取用户信息
     */
    @GetMapping("/{userId}")
    public ResponseEntity<Map<String, Object>> getUserInfo(@PathVariable Long userId) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            UserEntity user = userService.getUserById(userId);
            
            if (user != null) {
                response.put("code", 1);
                response.put("msg", "获取成功");
                response.put("data", user);
            } else {
                response.put("code", 0);
                response.put("msg", "用户不存在");
            }
            
        } catch (Exception e) {
            logger.error("获取用户信息时发生错误", e);
            response.put("code", 0);
            response.put("msg", "获取用户信息失败");
        }
        
        return ResponseEntity.ok(response);
    }
    
    /**
     * 获取当前登录用户信息
     */
    @GetMapping("/current")
    public ResponseEntity<Map<String, Object>> getCurrentUser(
            @RequestHeader("Authorization") String token) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            String username = jwtUtils.getUsernameFromToken(token.replace("Bearer ", ""));
            if (username == null) {
                response.put("code", 0);
                response.put("msg", "无效的token");
                return ResponseEntity.ok(response);
            }
            
            UserEntity user = userService.getUserByUsername(username);
            
            if (user != null) {
                response.put("code", 1);
                response.put("msg", "获取成功");
                response.put("data", user);
            } else {
                response.put("code", 0);
                response.put("msg", "用户不存在");
            }
            
        } catch (Exception e) {
            logger.error("获取当前用户信息时发生错误", e);
            response.put("code", 0);
            response.put("msg", "获取用户信息失败");
        }
        
        return ResponseEntity.ok(response);
    }
    
    /**
     * 通过用户名获取用户信息
     */
    @GetMapping("/by-username")
    public ResponseEntity<Map<String, Object>> getUserByUsername(@RequestParam String username) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            UserEntity user = userService.getUserByUsername(username);
            
            if (user != null) {
                response.put("code", 1);
                response.put("msg", "获取成功");
                response.put("data", user);
            } else {
                response.put("code", 0);
                response.put("msg", "用户不存在");
            }
            
        } catch (Exception e) {
            logger.error("通过用户名获取用户信息时发生错误", e);
            response.put("code", 0);
            response.put("msg", "获取用户信息失败");
        }
        
        return ResponseEntity.ok(response);
    }
    
    /**
     * 获取所有用户列表
     */
    @GetMapping
    public ResponseEntity<Map<String, Object>> getAllUsers() {
        Map<String, Object> response = new HashMap<>();
        
        try {
            List<UserEntity> users = userService.getAllUsers();
            
            response.put("code", 1);
            response.put("msg", "获取成功");
            response.put("data", users);
            
            logger.info("获取用户列表成功，共{}个用户", users.size());
            
        } catch (Exception e) {
            logger.error("获取用户列表时发生错误", e);
            response.put("code", 0);
            response.put("msg", "获取用户列表失败");
        }
        
        return ResponseEntity.ok(response);
    }
    
    /**
     * 更新用户个人信息
     */
    @PutMapping("/update-profile")
    public ResponseEntity<Map<String, Object>> updateUserProfile(
            @RequestBody UserEntity user,
            @RequestHeader("Authorization") String token) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            String username = jwtUtils.getUsernameFromToken(token.replace("Bearer ", ""));
            if (username == null) {
                response.put("code", 0);
                response.put("msg", "无效的token");
                return ResponseEntity.ok(response);
            }
            
            // 获取当前用户信息
            UserEntity currentUser = userService.getUserByUsername(username);
            if (currentUser == null) {
                response.put("code", 0);
                response.put("msg", "用户不存在");
                return ResponseEntity.ok(response);
            }
            
            // 设置用户ID，确保只能更新自己的信息
            user.setId(currentUser.getId());
            
            boolean success = userService.updateUserProfile(user);
            
            if (success) {
                response.put("code", 1);
                response.put("msg", "更新成功");
                
                // 返回更新后的用户信息
                UserEntity updatedUser = userService.getUserById(currentUser.getId().longValue());
                response.put("data", updatedUser);
                
                logger.info("用户 {} 更新个人信息成功", username);
            } else {
                response.put("code", 0);
                response.put("msg", "更新失败");
                logger.warn("用户 {} 更新个人信息失败", username);
            }
            
        } catch (Exception e) {
            logger.error("更新用户个人信息时发生错误", e);
            response.put("code", 0);
            response.put("msg", "更新失败，请稍后重试");
        }
        
        return ResponseEntity.ok(response);
    }
    
    /**
     * 删除用户
     */
    @DeleteMapping("/{userId}")
    public ResponseEntity<Map<String, Object>> deleteUser(
            @PathVariable Integer userId,
            @RequestHeader("Authorization") String token) {
        Map<String, Object> response = new HashMap<>();
        
        logger.info("[删除用户] 开始处理删除用户请求，用户ID: {}", userId);
        
        try {
            logger.info("[删除用户] 验证JWT token");
            String username = jwtUtils.getUsernameFromToken(token.replace("Bearer ", ""));
            if (username == null) {
                logger.warn("[删除用户] JWT token无效");
                response.put("code", 0);
                response.put("msg", "无效的token");
                return ResponseEntity.ok(response);
            }
            logger.info("[删除用户] JWT token验证成功，当前用户: {}", username);
            
            // 获取当前用户信息，验证是否有删除权限
            logger.info("[删除用户] 获取当前用户信息");
            UserEntity currentUser = userService.getUserByUsername(username);
            if (currentUser == null) {
                logger.warn("[删除用户] 当前用户不存在: {}", username);
                response.put("code", 0);
                response.put("msg", "用户不存在");
                return ResponseEntity.ok(response);
            }
            logger.info("[删除用户] 当前用户信息: ID={}, 用户名={}, 职位={}", currentUser.getId(), currentUser.getUsername(), currentUser.getJob());
            
            // 检查是否为管理员（job=1为班主任，具有管理权限）
            if (currentUser.getJob() != 1) {
                logger.warn("[删除用户] 权限不足，当前用户职位: {}", currentUser.getJob());
                response.put("code", 0);
                response.put("msg", "权限不足，只有班主任可以删除用户");
                return ResponseEntity.ok(response);
            }
            logger.info("[删除用户] 权限验证通过，当前用户为管理员");
            
            // 不能删除自己
            if (currentUser.getId().equals(userId)) {
                logger.warn("[删除用户] 尝试删除自己的账户，当前用户ID: {}, 目标用户ID: {}", currentUser.getId(), userId);
                response.put("code", 0);
                response.put("msg", "不能删除自己的账户");
                return ResponseEntity.ok(response);
            }
            
            // 检查要删除的用户是否存在
            logger.info("[删除用户] 检查目标用户是否存在，用户ID: {}", userId);
            UserEntity userToDelete = userService.getUserById(userId);
            if (userToDelete == null) {
                logger.warn("[删除用户] 目标用户不存在，用户ID: {}", userId);
                response.put("code", 0);
                response.put("msg", "要删除的用户不存在");
                return ResponseEntity.ok(response);
            }
            logger.info("[删除用户] 目标用户信息: ID={}, 用户名={}, 姓名={}", userToDelete.getId(), userToDelete.getUsername(), userToDelete.getName());
            
            logger.info("[删除用户] 开始执行删除操作，目标用户: {}", userToDelete.getUsername());
            boolean success = userService.deleteUser(userId);
            logger.info("[删除用户] 删除操作完成，结果: {}", success);
            
            if (success) {
                response.put("code", 1);
                response.put("msg", "删除成功");
                logger.info("[删除用户] 删除成功 - 操作者: {}, 被删除用户: {}", username, userToDelete.getUsername());
            } else {
                response.put("code", 0);
                response.put("msg", "删除失败");
                logger.error("[删除用户] 删除失败 - 操作者: {}, 目标用户: {}", username, userToDelete.getUsername());
            }
            
        } catch (Exception e) {
            logger.error("[删除用户] 删除用户时发生异常，用户ID: {}", userId, e);
            response.put("code", 0);
            response.put("msg", "删除失败，请稍后重试");
        }
        
        logger.info("[删除用户] 删除用户请求处理完成，用户ID: {}, 响应: {}", userId, response);
        return ResponseEntity.ok(response);
    }
    
    /**
     * 更新用户信息（管理员功能）
     */
    @PutMapping("/{userId}")
    public ResponseEntity<Map<String, Object>> updateUser(
            @PathVariable Integer userId,
            @RequestBody UserEntity user,
            @RequestHeader("Authorization") String token) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            String username = jwtUtils.getUsernameFromToken(token.replace("Bearer ", ""));
            if (username == null) {
                response.put("code", 0);
                response.put("msg", "无效的token");
                return ResponseEntity.ok(response);
            }
            
            // 获取当前用户信息，验证是否有编辑权限
            UserEntity currentUser = userService.getUserByUsername(username);
            if (currentUser == null) {
                response.put("code", 0);
                response.put("msg", "用户不存在");
                return ResponseEntity.ok(response);
            }
            
            // 检查是否为管理员（job=1为班主任，具有管理权限）
            if (currentUser.getJob() != 1) {
                response.put("code", 0);
                response.put("msg", "权限不足，只有班主任可以编辑用户信息");
                return ResponseEntity.ok(response);
            }
            
            // 检查要编辑的用户是否存在
            UserEntity userToUpdate = userService.getUserById(userId);
            if (userToUpdate == null) {
                response.put("code", 0);
                response.put("msg", "要编辑的用户不存在");
                return ResponseEntity.ok(response);
            }
            
            // 设置用户ID和更新时间
            user.setId(userId);
            user.setUpdateTime(new java.util.Date());
            
            // 保留原有的用户名和密码
            user.setUsername(userToUpdate.getUsername());
            user.setPassword(userToUpdate.getPassword());
            user.setCreateTime(userToUpdate.getCreateTime());
            
            boolean success = userService.updateUserProfile(user);
            
            if (success) {
                response.put("code", 1);
                response.put("msg", "更新成功");
                
                // 返回更新后的用户信息
                UserEntity updatedUser = userService.getUserById(userId);
                response.put("data", updatedUser);
                
                logger.info("用户 {} 更新了用户 {} 的信息", username, userToUpdate.getUsername());
            } else {
                response.put("code", 0);
                response.put("msg", "更新失败");
                logger.warn("用户 {} 更新用户 {} 信息失败", username, userToUpdate.getUsername());
            }
            
        } catch (Exception e) {
            logger.error("更新用户信息时发生错误", e);
            response.put("code", 0);
            response.put("msg", "更新失败，请稍后重试");
        }
        
        return ResponseEntity.ok(response);
    }
}